from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from uuid import UUID
from datetime import datetime

from app.database.base import get_db
from app.schemas.maintenance_plan import (
    MaintenancePlanCreate, 
    MaintenancePlanUpdate, 
    MaintenancePlanResponse,
    MaintenancePlanFilter,
    MaintenancePlanExecution
)
from app.models.maintenance_record import MaintenanceType
from app.models.maintenance_plan import PlanFrequency
from app.services.maintenance_plan import MaintenancePlanService
from app.core.auth import get_current_user
from app.models.user import User

router = APIRouter(prefix="/maintenance-plans", tags=["maintenance-plans"])
plan_service = MaintenancePlanService()

@router.post("/save", response_model=MaintenancePlanResponse, status_code=status.HTTP_201_CREATED)
async def create_maintenance_plan(
    plan_data: MaintenancePlanCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建维护计划"""
    try:
        return plan_service.create(db, obj_in=plan_data, created_by=current_user.id)  # type: ignore
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/list", response_model=List[MaintenancePlanResponse])
async def get_maintenance_plans(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    device_id: Optional[UUID] = None,
    maintenance_type: Optional[MaintenanceType] = None,
    frequency: Optional[PlanFrequency] = None,
    is_active: Optional[bool] = None,
    default_assignee: Optional[UUID] = None,
    due_soon: Optional[bool] = None,
    overdue: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取维护计划列表"""
    filters = MaintenancePlanFilter(
        device_id=device_id,
        maintenance_type=maintenance_type,
        frequency=frequency,
        is_active=is_active,
        default_assignee=default_assignee,
        due_soon=due_soon,
        overdue=overdue
    )
    
    return plan_service.get_multi(db, skip=skip, limit=limit, filters=filters)

@router.get("/due", response_model=List[MaintenancePlanResponse])
async def get_due_plans(
    advance_days: int = Query(0, ge=0, le=30, description="提前天数"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取到期的维护计划"""
    return plan_service.get_due_plans(db, advance_days=advance_days)

@router.get("/{plan_id}", response_model=MaintenancePlanResponse)
async def get_maintenance_plan(
    plan_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取维护计划详情"""
    plan = plan_service.get(db, plan_id)
    if not plan:
        raise HTTPException(status_code=404, detail="维护计划不存在")
    return plan

@router.put("/{plan_id}", response_model=MaintenancePlanResponse)
async def update_maintenance_plan(
    plan_id: UUID,
    plan_data: MaintenancePlanUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新维护计划"""
    plan = plan_service.get(db, plan_id)
    if not plan:
        raise HTTPException(status_code=404, detail="维护计划不存在")
    
    try:
        return plan_service.update(db, db_obj=plan, obj_in=plan_data)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/{plan_id}/activate", response_model=MaintenancePlanResponse)
async def activate_plan(
    plan_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """激活维护计划"""
    plan = plan_service.activate_plan(db, plan_id=plan_id)
    if not plan:
        raise HTTPException(status_code=404, detail="维护计划不存在")
    return plan

@router.post("/{plan_id}/deactivate", response_model=MaintenancePlanResponse)
async def deactivate_plan(
    plan_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """停用维护计划"""
    plan = plan_service.deactivate_plan(db, plan_id=plan_id)
    if not plan:
        raise HTTPException(status_code=404, detail="维护计划不存在")
    return plan

@router.post("/{plan_id}/execute", response_model=MaintenancePlanExecution)
async def execute_plan(
    plan_id: UUID,
    execution_date: Optional[datetime] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """执行维护计划（创建维护记录）"""
    try:
        execution = plan_service.execute_plan(
            db, 
            plan_id=plan_id, 
            execution_date=execution_date,
            created_by=current_user.id  # type: ignore
        )
        if not execution:
            raise HTTPException(status_code=404, detail="维护计划不存在")
        return execution
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/auto-create-records", response_model=List[MaintenancePlanExecution])
async def auto_create_maintenance_records(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """自动创建到期的维护记录（管理员功能）"""
    if current_user.role not in ["admin", "manager"]:
        raise HTTPException(status_code=403, detail="权限不足")
    
    try:
        executions = plan_service.auto_create_maintenance_records(db, created_by=current_user.id)  # type: ignore
        return executions
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{plan_id}")
async def delete_maintenance_plan(
    plan_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除维护计划"""
    plan = plan_service.remove(db, id=plan_id)
    if not plan:
        raise HTTPException(status_code=404, detail="维护计划不存在")
    
    return {"message": "维护计划删除成功"}